<template>
  <div class="gray-release-container">
    <div class="page-header">
      <h1>灰度发布管理</h1>
      <p class="subtitle">管理微前端应用的灰度白名单和版本绑定</p>
    </div>

    <el-card class="main-card">
      <!-- 应用选择 -->
      <div class="app-selector">
        <el-select
          v-model="selectedAppId"
          placeholder="选择应用"
          style="width: 200px"
          @change="handleAppChange"
        >
          <el-option
            v-for="app in appList"
            :key="app.id"
            :label="app.name"
            :value="app.id"
          />
        </el-select>
        <el-button type="primary" @click="handleAdd" style="margin-left: 12px">
          <el-icon><Plus /></el-icon>
          添加灰度绑定
        </el-button>
        <el-button type="danger" @click="handleClearAll" :disabled="!selectedAppId">
          <el-icon><Delete /></el-icon>
          清理所有
        </el-button>
        <el-button @click="handleRefresh" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>

      <!-- 版本统计 -->
      <el-card v-if="selectedAppId && versionStats" class="stats-card" shadow="never">
        <template #header>
          <span>版本统计</span>
        </template>
        <div class="stats-content">
          <div class="stat-item">
            <span class="stat-label">总版本数：</span>
            <span class="stat-value">{{ versionStats.totalVersions }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">总用户数：</span>
            <span class="stat-value">{{ versionStats.totalUsers }}</span>
          </div>
        </div>
        <el-table :data="versionStats.stats" style="margin-top: 16px" size="small" border>
          <el-table-column prop="version" label="版本号" width="150" />
          <el-table-column prop="userCount" label="用户数量" width="120" />
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button
                type="primary"
                link
                size="small"
                @click="viewVersionUsers(scope.row.version)"
              >
                查看用户
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 灰度白名单列表 -->
      <el-table
        v-if="selectedAppId"
        :data="grayReleaseList"
        style="margin-top: 20px"
        v-loading="loading"
        border
      >
        <el-table-column prop="userId" label="用户ID" width="200" />
        <el-table-column prop="version" label="版本号" width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无灰度白名单数据" />
        </template>
      </el-table>

      <el-empty v-if="!selectedAppId" description="请选择应用" />
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingItem ? '编辑灰度绑定' : '添加灰度绑定'"
      width="500px"
      @opened="handleDialogOpened"
    >
      <el-form :model="formData" label-width="100px">
        <el-form-item label="应用ID">
          <el-input v-model="formData.appId" :disabled="!!editingItem" />
        </el-form-item>
        <el-form-item label="用户" v-if="!isBatchMode">
          <el-select
            v-model="formData.userId"
            placeholder="请选择用户"
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userSearchLoading"
            style="width: 100%"
            :disabled="!!editingItem"
            clearable
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="getUserLabel(user)"
              :value="String(user.id)"
            >
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span>{{ getUserLabel(user) }}</span>
                <el-tag v-if="user.profile?.email" size="small" type="info" style="margin-left: 8px;">
                  {{ user.profile.email }}
                </el-tag>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户列表" v-else>
          <el-select
            v-model="selectedUserIds"
            placeholder="请选择用户（可多选）"
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userSearchLoading"
            multiple
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="getUserLabel(user)"
              :value="String(user.id)"
            >
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span>{{ getUserLabel(user) }}</span>
                <el-tag v-if="user.profile?.email" size="small" type="info" style="margin-left: 8px;">
                  {{ user.profile.email }}
                </el-tag>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本号">
          <el-input v-model="formData.version" placeholder="如：v1.2.0" />
        </el-form-item>
        <el-form-item label="过期时间（秒）">
          <el-input-number
            v-model="formData.ttl"
            :min="0"
            placeholder="0表示不过期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="isBatchMode" @change="handleBatchModeChange">批量模式</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="saving">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看版本用户对话框 -->
    <el-dialog v-model="showUsersDialog" title="版本用户列表" width="600px">
      <el-table :data="versionUsers" max-height="400" border>
        <el-table-column prop="userId" label="用户ID" />
      </el-table>
      <template #footer>
        <el-button @click="showUsersDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete, Refresh } from '@element-plus/icons-vue';
import { grayReleaseApi, GrayReleaseBinding, VersionStats } from '../api/grayRelease';
import { userApi, User } from '../api/user';

// 应用列表
const appList = [
  { id: 'vue-app1', name: '全域管理' },
  { id: 'vue-app2', name: '应用二' },
  { id: 'vue-build', name: '构建中心' },
  { id: 'react-devops', name: 'DevOps BI' },
  { id: 'vue-devops', name: '埋点中心' },
  { id: 'vue-base', name: '基础应用' },
];

const selectedAppId = ref('');
const grayReleaseList = ref<GrayReleaseBinding[]>([]);
const versionStats = ref<VersionStats | null>(null);
const loading = ref(false);
const saving = ref(false);
const showAddDialog = ref(false);
const showUsersDialog = ref(false);
const editingItem = ref<GrayReleaseBinding | null>(null);
const isBatchMode = ref(false);
const versionUsers = ref<string[]>([]);
const selectedUserIds = ref<string[]>([]);
const userOptions = ref<User[]>([]);
const userSearchLoading = ref(false);
const userSearchKeyword = ref('');

const formData = ref({
  appId: '',
  userId: '',
  version: '',
  ttl: undefined as number | undefined,
});

// 应用切换
const handleAppChange = async () => {
  if (!selectedAppId.value) return;
  formData.value.appId = selectedAppId.value;
  await loadGrayReleaseList();
  await loadVersionStats();
};

// 刷新数据
const handleRefresh = async () => {
  await handleAppChange();
};

// 加载灰度白名单列表
const loadGrayReleaseList = async () => {
  if (!selectedAppId.value) return;
  
  loading.value = true;
  try {
    const res = await grayReleaseApi.queryGrayRelease({
      appId: selectedAppId.value,
    });
    if (res && res.code === 200) {
      grayReleaseList.value = res.data?.bindings || [];
    } else {
      ElMessage.warning('加载灰度白名单失败：' + (res?.message || '未知错误'));
      grayReleaseList.value = [];
    }
  } catch (error: any) {
    console.error('加载灰度白名单失败:', error);
    const errorMsg = error?.response?.data?.message || error?.message || '加载灰度白名单失败';
    if (error?.response?.status === 403) {
      ElMessage.warning('权限不足，无法查看灰度白名单');
    } else {
      ElMessage.error(errorMsg);
    }
    grayReleaseList.value = [];
  } finally {
    loading.value = false;
  }
};

// 加载版本统计
const loadVersionStats = async () => {
  if (!selectedAppId.value) return;
  
  try {
    const res = await grayReleaseApi.getVersionStats(selectedAppId.value);
    if (res && res.code === 200) {
      versionStats.value = res.data;
    } else {
      versionStats.value = null;
    }
  } catch (error: any) {
    console.error('加载版本统计失败：', error);
    versionStats.value = null;
  }
};

// 查看版本用户
const viewVersionUsers = async (version: string) => {
  if (!selectedAppId.value) return;
  
  try {
    const res = await grayReleaseApi.getUsersByVersion(selectedAppId.value, version);
    if (res && res.code === 200) {
      versionUsers.value = res.data?.users || [];
      showUsersDialog.value = true;
    } else {
      ElMessage.error('查询用户列表失败：' + (res?.message || '未知错误'));
    }
  } catch (error: any) {
    console.error('查询用户列表失败:', error);
    ElMessage.error('查询用户列表失败：' + (error?.message || '未知错误'));
  }
};

// 添加/编辑
const handleEdit = async (item: GrayReleaseBinding) => {
  editingItem.value = item;
  formData.value = {
    appId: selectedAppId.value,
    userId: item.userId,
    version: item.version,
    ttl: undefined,
  };
  isBatchMode.value = false;
  
  // 加载用户列表，并选中当前用户
  await searchUsers();
  // 尝试找到当前用户并添加到选项中（如果不在列表中）
  const currentUserId = parseInt(item.userId);
  if (!isNaN(currentUserId) && !userOptions.value.find(u => u.id === currentUserId)) {
    try {
      const userRes = await userApi.getUserDetail(currentUserId);
      if (userRes && userRes.code === 200 && userRes.data) {
        userOptions.value.unshift(userRes.data);
      }
    } catch (error) {
      console.error('获取用户详情失败:', error);
    }
  }
  
  showAddDialog.value = true;
};

// 删除
const handleDelete = async (item: GrayReleaseBinding) => {
  try {
    await ElMessageBox.confirm('确定要删除这个灰度绑定吗？', '提示', {
      type: 'warning',
    });
    
    const res = await grayReleaseApi.deleteGrayRelease({
      appId: selectedAppId.value,
      userId: item.userId,
    });
    
    if (res && res.code === 200) {
      ElMessage.success('删除成功');
      await loadGrayReleaseList();
      await loadVersionStats();
    } else {
      ElMessage.error('删除失败：' + (res?.message || '未知错误'));
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败：' + (error?.message || '未知错误'));
    }
  }
};

// 清理所有
const handleClearAll = async () => {
  try {
    await ElMessageBox.confirm('确定要清理该应用的所有灰度白名单吗？', '警告', {
      type: 'warning',
    });
    
    const res = await grayReleaseApi.clearAppGrayRelease(selectedAppId.value);
    
    if (res && res.code === 200) {
      ElMessage.success('清理成功');
      await loadGrayReleaseList();
      await loadVersionStats();
    } else {
      ElMessage.error('清理失败：' + (res?.message || '未知错误'));
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('清理失败:', error);
      ElMessage.error('清理失败：' + (error?.message || '未知错误'));
    }
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formData.value.appId || !formData.value.version) {
    ElMessage.warning('请填写应用ID和版本号');
    return;
  }

  saving.value = true;
  try {
    if (isBatchMode.value) {
      // 批量绑定
      if (selectedUserIds.value.length === 0) {
        ElMessage.warning('请至少选择一个用户');
        saving.value = false;
        return;
      }
      
      const res = await grayReleaseApi.batchBindGrayRelease({
        appId: formData.value.appId,
        userIds: selectedUserIds.value,
        version: formData.value.version,
        ttl: formData.value.ttl,
      });
      
      if (res && res.code === 200) {
        ElMessage.success('批量绑定成功');
        showAddDialog.value = false;
        resetForm();
        await loadGrayReleaseList();
        await loadVersionStats();
      } else {
        ElMessage.error('批量绑定失败：' + (res?.message || '未知错误'));
      }
    } else if (editingItem.value) {
      // 更新
      if (!formData.value.userId) {
        ElMessage.warning('请填写用户ID');
        saving.value = false;
        return;
      }

      const res = await grayReleaseApi.updateGrayRelease(formData.value);
      
      if (res && res.code === 200) {
        ElMessage.success('更新成功');
        showAddDialog.value = false;
        resetForm();
        await loadGrayReleaseList();
        await loadVersionStats();
      } else {
        ElMessage.error('更新失败：' + (res?.message || '未知错误'));
      }
    } else {
      // 创建
      if (!formData.value.userId) {
        ElMessage.warning('请填写用户ID');
        saving.value = false;
        return;
      }

      const res = await grayReleaseApi.createGrayRelease(formData.value);
      
      if (res && res.code === 200) {
        ElMessage.success('创建成功');
        showAddDialog.value = false;
        resetForm();
        await loadGrayReleaseList();
        await loadVersionStats();
      } else {
        ElMessage.error('创建失败：' + (res?.message || '未知错误'));
      }
    }
  } catch (error: any) {
    console.error('操作失败:', error);
    const errorMsg = error?.response?.data?.message || error?.message || '操作失败';
    ElMessage.error(errorMsg);
  } finally {
    saving.value = false;
  }
};

// 搜索用户
const searchUsers = async (query?: string) => {
  userSearchKeyword.value = query || '';
  userSearchLoading.value = true;
  
  try {
    const params: any = {
      pageSize: 50,
      pageNo: 1,
    };
    
    if (query) {
      params.username = query;
    }
    
    const res = await userApi.getUserList(params);
    if (res && res.code === 200) {
      userOptions.value = res.data?.pageData || [];
    } else {
      userOptions.value = [];
    }
  } catch (error: any) {
    console.error('搜索用户失败:', error);
    userOptions.value = [];
  } finally {
    userSearchLoading.value = false;
  }
};

// 获取用户显示标签
const getUserLabel = (user: User): string => {
  const parts: string[] = [];
  if (user.username) parts.push(user.username);
  if (user.profile?.nickName) parts.push(`(${user.profile.nickName})`);
  if (parts.length === 0) parts.push(`用户${user.id}`);
  return parts.join(' ');
};

// 重置表单
const resetForm = () => {
  editingItem.value = null;
  isBatchMode.value = false;
  selectedUserIds.value = [];
  userOptions.value = [];
  userSearchKeyword.value = '';
  formData.value = {
    appId: selectedAppId.value || '',
    userId: '',
    version: '',
    ttl: undefined,
  };
};

// 监听批量模式切换
const handleBatchModeChange = () => {
  if (isBatchMode.value) {
    // 切换到批量模式，清空单个用户选择
    formData.value.userId = '';
  } else {
    // 切换到单个模式，清空批量用户选择
    selectedUserIds.value = [];
  }
};

// 添加按钮点击
const handleAdd = () => {
  resetForm();
  formData.value.appId = selectedAppId.value || '';
  showAddDialog.value = true;
};

// 对话框打开时加载用户列表
const handleDialogOpened = () => {
  if (userOptions.value.length === 0) {
    searchUsers();
  }
};

// 初始化
onMounted(() => {
  // 初始加载用户列表（显示前50个用户）
  searchUsers();
});
</script>

<style scoped>
.gray-release-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 28px;
  color: var(--el-color-primary);
  margin: 0 0 8px 0;
}

.subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.main-card {
  margin-top: 20px;
}

.app-selector {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.stats-card {
  margin-top: 20px;
}

.stats-content {
  display: flex;
  gap: 24px;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-right: 8px;
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-color-primary);
}
</style>

